﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Web;

namespace CDEPMS_API.Utils
{
    public class JwtHelper
    {
        private static string SecretKey => ConfigurationManager.AppSettings["AuthSecretKey"];
        private static string Issuer => ConfigurationManager.AppSettings["AuthIssuer"];
        private const string Audience = "pms";

        public static string GenerateToken(string userId, string role, int expireMinutes)
        {
            var key = Encoding.UTF8.GetBytes(SecretKey);
            if (key.Length < 32) throw new ArgumentException("密钥长度不足256位（32字节）");

            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                new Claim(ClaimTypes.NameIdentifier, userId),
                new Claim(ClaimTypes.Role, role)
            }),
                Expires = DateTime.UtcNow.AddMinutes(expireMinutes),
                Issuer = Issuer,
                Audience = Audience,
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(key),
                    SecurityAlgorithms.HmacSha256
                )
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }

        public static ClaimsPrincipal ValidateToken(string token)
        {
            var key = Encoding.UTF8.GetBytes(SecretKey);
            if (key.Length < 32) throw new ArgumentException("密钥长度不足256位（32字节）");

            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = true,
                ValidIssuer = Issuer,
                ValidateAudience = true,
                ValidAudience = Audience,
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero,
                NameClaimType = ClaimTypes.NameIdentifier,  // 关键修复
                ValidAlgorithms = new[] { SecurityAlgorithms.HmacSha256 }  // 强制算法
            };

            try
            {
                return tokenHandler.ValidateToken(token, validationParameters, out _);
            }
            catch (SecurityTokenException ex)
            {
                throw new SecurityTokenException($"JWT验证失败: {ex.Message}", ex);
            }
        }
    }

}